package com.zhanglifan.service.impl;

import com.zhanglifan.domain.Contract;
import com.zhanglifan.domain.ContractProduct;
import com.zhanglifan.domain.ExtCproduct;
import com.zhanglifan.service.ContractProductService;
import com.zhanglifan.util.UtilFuns;

import java.io.Serializable;
import java.util.List;

/**
 * Information
 * Author: ZhangLifan
 * Time: 2017/10/6 8:50
 * Description: ContractServiceImpl
 */
public class ContractProductServiceImpl extends BaseServiceImpl<ContractProduct> implements ContractProductService {

    @Override
    public void saveOrUpdate(ContractProduct entity) {
        double totle = 0.0;
        if(UtilFuns.isNotEmpty(entity.getCnumber()) && UtilFuns.isNotEmpty(entity.getPrice())){
            totle = entity.getPrice()*entity.getCnumber();
        }
        if (UtilFuns.isEmpty(entity.getId())){
            entity.setAmount(totle);
            Contract contract = (Contract) baseDao.get(Contract.class,entity.getContract().getId());
            contract.setTotalAmount((contract.getTotalAmount()==null ? 0 : contract.getTotalAmount()) + totle);
            baseDao.saveOrUpdate(contract);
        }else{
            double oldAmount = entity.getAmount();
            Contract contract = (Contract) baseDao.get(Contract.class,entity.getContract().getId());
            contract.setTotalAmount((contract.getTotalAmount()==null ? 0 : contract.getTotalAmount()) - oldAmount + totle);
            entity.setAmount(totle);
            baseDao.saveOrUpdate(contract);
        }

        super.saveOrUpdate(entity);
    }


    @Override
    public void deleteById(Class<ContractProduct> entityClass, Serializable id) {
        ContractProduct contractProduct = get(ContractProduct.class, id);
        double amount = contractProduct.getAmount() == null ? 0.0 : contractProduct.getAmount();
        List<ExtCproduct> extList = baseDao.find("from ExtCproduct where contractProduct.id=?",ExtCproduct.class,new String[]{contractProduct.getId()});
        for (ExtCproduct ext : extList) {
            amount+=ext.getAmount()==null ? 0.0 : ext.getAmount();
        }
        Contract contract = (Contract) baseDao.get(Contract.class,contractProduct.getContract().getId());
        contract.setTotalAmount((contract.getTotalAmount()==null ? 0 : contract.getTotalAmount())-amount);
        super.deleteById(entityClass, id);
    }
}
